/*
 * @Description: 文件描述
 * @Version: 1.0
 * @Author: YueXuanzi
 * @Date: 2024-09-09 15:02:34
 * @LastEditors: YueXuanzi
 * @LastEditTime: 2024-09-22 15:55:07
 * @心得体会: 无
 */
import axios from 'axios'
import { ElNotification, ElMessage, ElMessageBox } from 'element-plus'
import {useCookies} from '@vueuse/integrations/useCookies';

const service = axios.create({
  baseURL: '/api',
  timeout: 300000,
  headers: {
      'Content-Type': 'application/json',
  },
})


// 添加拦截器
service.interceptors.request.use(

    config => {
        const cookie = useCookies();
        const token = cookie.get('token')
        if(token){
            config.headers["token"] = token
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code === 401) {
            ElMessageBox.confirm('登录状态已过期，请您重新登录', '系统提示', {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              store.dispatch('/logout').then(() => {
                location.reload()
              })
            console.log("退出登录")
            })
          } else if (res.code !== 200) {
            ElMessage({
              message: res.msg || '系统异常',
              type: 'error',
              duration: 2000
            })
        } else {
            return res
        }
    },
    error => {
        console.log(error)
        ElNotification.error({
            title: '错误',
            message: error.msg || "请求错误",
            duration: 2000
        });
        return Promise.reject(error)
    }
)


export default service 
